package com.hqyj.demo.utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.demo.entity.Admin;
import com.hqyj.demo.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class AdminRealm extends AuthorizingRealm {
    /**
     * 权限
     * @param principalCollection
     * @return
     */

    @Autowired
    private AdminService adminService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        //权限
//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
//        //添加角色
//        List<String> roles = new ArrayList<>();
//        roles.add("dept");
//        simpleAuthorizationInfo.addRoles(roles);
//        //角色拥有的操作权限
//        List<String> permissions = new ArrayList<>();
//        permissions.add("dept:add");
//        simpleAuthorizationInfo.addStringPermissions(permissions);
////      拥有的权限

        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("----认证处理----");
        //获取当前系统登录的用户名
        String principal = (String) authenticationToken.getPrincipal();//用户名
        //封装查询参数
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        //字段名
        adminQueryWrapper.eq("username",principal);
        //通过用户名去查询数据库,验证用户名
        Admin admin = adminService.getOne(adminQueryWrapper);
        if(admin!=null){
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),
                            ByteSource.Util.bytes("abcd"),getName());
            SecurityUtils.getSubject().getSession().setAttribute(CacheConstantsKey.LOGIN_TOKEN_KEY,admin);
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
